package com.manong.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.manong.config.security.exception.CustomerAuthenticationException;
import com.manong.entity.LoginLog;
import com.manong.service.LoginLogService;
import com.manong.utils.IpAddressUtil;
import com.manong.utils.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 登录认证失败处理器
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Resource
    private LoginLogService loginLogService;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        //获取输出流
        ServletOutputStream out = response.getOutputStream();
        String message ;
        int code = 500;
        //判断异常类型
        if(exception instanceof AccountExpiredException){
            message = "账户过期,登录失败！";
        }else if(exception instanceof BadCredentialsException){
            message = "用户名或密码错误,登录失败！";
        }else if(exception instanceof CredentialsExpiredException){
            message = "密码过期,登录失败！";
        }else if(exception instanceof DisabledException){
            message = "账户被禁用,登录失败！";
        }else if(exception instanceof LockedException){
            message = "账户被锁,登录失败！";
        }else if(exception instanceof InternalAuthenticationServiceException){
            message = "账户不存在,登录失败！";
        }else if(exception instanceof CustomerAuthenticationException){
            message = exception.getMessage();
            code = 600;
        }
        else{
            message = "登录失败！";
        }
        String username = request.getParameter("username");
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(username);
        loginLog.setStatus('1');
        loginLog.setIpaddr(IpAddressUtil.getClientIPv4(request).equals("0:0:0:0:0:0:0:1")?"127.0.0.1":IpAddressUtil.getClientIPv4(request));
        loginLog.setOs(request.getHeader("sec-ch-ua-platform").replace("\"",""));
        loginLog.setMsg(message);
        loginLog.setLoginTime(new Date());
        loginLogService.save(loginLog); //记录登录失败日志

        String result = JSON.toJSONString(Result.error().code(code).message(message));
        out.write(result.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
